<style>
  #stripe-element {
    margin-bottom: 14px;
    min-height: 100px;
  }
</style>

<div id="stripe-form" style="position: relative; width: 100%">
  <div id="stripe-element"></div>
  <div id="stripe-button"></div>
  <div id="payment-message" style="margin-top: 14px;"></div>
</div>

<script language="javascript">
  $(function () {
    let elements;
    let stripe;

    $.createPaymentCard({
      src: "https://js.stripe.com/v3/",
      button: "#stripe-button",
      form: "#stripe-form",
      async scriptSuccess({ disableButton, enabledButton }) {
        disableButton();
        stripe = Stripe("{$this->payment->interface_type_param->key}");
        // 检查链接是否包含payment_intent_client_secret 验证返回状态
        const clientSecret = new URLSearchParams(window.location.search).get(
          "payment_intent_client_secret"
        );
        if (clientSecret) {
          const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

          switch (paymentIntent.status) {
            case "succeeded":
              await fetch("{$interfaceCallback}&id=" + paymentIntent.id, {
                method: "GET"
              })
              $.toast({ container: "#payment-message", text: "Payment succeeded!" })
              parent.location.href = "{$successUrl}";
              break;
            case "processing":
              $.toast({ container: "#payment-message", text: "Your payment is processing." })
              break;
            case "requires_payment_method":
              $.toast({ container: "#payment-message", text: "Your payment was not successful, please try again." })
              break;
            default:
              $.toast({ container: "#payment-message", text: "Something went wrong." })
              break;
          }
          return;
        }

        const options = {
          paymentMethodTypes: ['card'],
          mode: 'payment',
          currency: '{$currency}',
          amount: $payamount,
        };
        elements = stripe.elements(options);
        const paymentElement = elements.create("payment", {
          fields: {
            billingDetails: {
              address: 'never'
            }
          }
        });
        paymentElement.mount("#stripe-element");
        paymentElement.on('ready', function (event) {
          enabledButton()
        });
        setInterval(() => {
            var height = document.getElementById('payment-form').offsetHeight;
            if(height){
              window.parent.postMessage({type:"stripeAB",code:400,data:height},'*');
            }
        }, 500);
        
      },
      async verified() {
        const { error: submitError } = await elements.submit();
        if (submitError) {
          return false;
        }
        return true

      },
      async submit({ showLoading, hideLoading }) {
        showLoading()
        const { clientSecret, msg } = await fetch("{$create}", {
          method: "POST",
          headers: { "Content-Type": "application/json" }
        }).then((r) => r.json())
        if (msg) {
          $.toast({ container: "#payment-message", text: msg })
          hideLoading();
          return
        }
        const { error } = await stripe.confirmPayment({
          elements,
          clientSecret,
          confirmParams: {
            return_url: "{$this->domain}/checkouts/payment/stripe/return?checkout_token={$order->checkout_token}&order_number={$order->order_number}&payment_id={$order->payment_id}&local_token={$this->token}",
            payment_method_data: {
              billing_details: {
                address: {
                  "city": "{$billingAddress['city']}",
                  "country": "{$billingAddress['country_code']}",
                  "line1": "{$billingAddress['address1']}",
                  "line2": "{$billingAddress['address2']}",
                  "postal_code": "{$billingAddress['zip']}",
                  "state": "{$billingAddress['province_code']}"
                }
              }
            }
          },
        });

        const error_code = ['testmode_charges_only', 'bank_account_declined', 'api_key_expired', 'platform_api_key_expired', 'bank_account_unusable', 'charge_exceeds_source_limit', 'expired_card', 'refer_to_customer'];
        if (error.type === "card_error" || error.type === "validation_error") {
          $.toast({ container: "#payment-message", text: error.message })

        } else if (error_code.indexOf(error.code.toLowerCase()) > -1) {
          await fetch("{$errorCallback}&msg=" + error.code, { method: "GET" })
          $.toast({ container: "#payment-message", text: "An unexpected error occured." })
        } else {
          $.toast({ container: "#payment-message", text: "An unexpected error occured." })
        }
        hideLoading();
      }
    })
  })
</script>